package com.itcncp.ipaybox.server.resolver;

import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.itcncp.common.ipaybox.BoxConstants;
import com.itcncp.common.ipaybox.model.BoxRequest;
import com.itcncp.common.ipaybox.model.BoxResponse;
import com.itcncp.ipaybox.trans.dubbo.service.DubboService;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;

/**
 * 发送app线程
 * 
 * @author LiuPeng
 * @date 2017年12月19日
 * 
 */
public class Send2AppThread extends Thread {

	private ChannelHandlerContext channelHandlerContext;

	private BoxRequest boxRequest;

	private DubboService itcsApp;

	public Send2AppThread(DubboService itcsApp, ChannelHandlerContext channelHandlerContext, BoxRequest boxRequest) {
		this.channelHandlerContext = channelHandlerContext;
		this.boxRequest = boxRequest;
		this.itcsApp = itcsApp;
		
		InetSocketAddress socketAddress = (InetSocketAddress) channelHandlerContext.channel().remoteAddress();
		boxRequest.initChnanel(socketAddress.getHostString(), String.valueOf(socketAddress.getPort()), String.valueOf(channelHandlerContext.channel().id()));
	}

	@Override
	public void run() {
		Map<String, Object> reqRecord = new HashMap<>();
		try {
			String messageType = boxRequest.getMessgeType();
			String tranId = "box_" + messageType;
			reqRecord.put(BoxConstants.BOX_REQ_KEY, boxRequest);
			Map<String, Object> resMap = itcsApp.exchange(tranId, reqRecord);
			Object res = resMap.get(BoxConstants.BOX_RES_KEY);
			if (res != null) {
				BoxResponse boxResponse = (BoxResponse) resMap.get(BoxConstants.BOX_RES_KEY);
				ByteBuf byteBuf = Unpooled
						.wrappedBuffer(JSON.toJSONString(boxResponse).getBytes(BoxConstants.CHARSET_UTF8));
				channelHandlerContext.writeAndFlush(byteBuf);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}